<template>
  <div
    class="help-manual-snippet"
    :style="boxStyle"
  >
    <div
      class="desc"
      :snippetKey="snippetKey"
      v-html="xssValueFilter(snippet)"
    ></div>
  </div>
</template>
<script>
import { getHelpManualBaseUrl } from '@/components/common/help-manual/help-manual-util.js';
import storage from '@/utils/ado-self/ado-storage';
import { getLang } from '@/utils/lang.js';
import { objHas, xssValueFilter } from '@/utils/util.js';

const { helpManual: helpConf = {} } = window.localVars || {};

// 本地缓存时间： 测试环境10秒，其他环境1小时
const STORAGE_TIMEOUT = window.isLocalEnv ? 1000 * 10 : 1000 * 60 * 60;
const STORAGE_KEY = 'visual_help_snippets';

export default {
  components: {},
  props: {
    snippetKey: String,
    boxStyle: {
      type: Object,
      default: () => ({}),
    },
    isDiySnippet: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      snippet: '',
      loadSnippetTimer: null,
    };
  },
  computed: {},
  watch: {
    snippet() {
      this.$emit('snippet-updated');
    },
  },
  created() {
    this.initSnippet();
  },
  mounted() {
    this.loadSnippet();
  },
  beforeUnmount() {
    clearTimeout(this.loadSnippetTimer);
  },
  methods: {
    xssValueFilter,
    initSnippet() {
      if (window.isLocalEnv || window.location.href.includes('debugger')) {
        this.snippet = `{#desc: ${this.snippetKey}}`;
      }
    },

    async loadSnippet() {
      const tips = await this.getTips();
      const tipKey = this.snippetKey;
      const { theme } = window._adoPremise.uc;
      const themeKey = `${tipKey}.${theme}`;
      if (this.isDiySnippet) {
        this.snippet = await this.getDiySnippet(tipKey);
      } else if (objHas(tips, themeKey)) {
        this.snippet = tips[themeKey];
      } else {
        this.snippet = tips[tipKey];
      }
    },

    getDiySnippet(tipKey) {
      const baseUrl = getHelpManualBaseUrl();
      const url = `${baseUrl}/diy_snippets/${tipKey}.html`;
      return new Promise(resolve => {
        fetch(url).then(res=>res.text()).then(data=>{
          const docEl = document.createElement('div');
          docEl.innerHTML = xssValueFilter(data);
          const lang = this.getLang();
          const html = docEl.querySelector(`.${lang}`)?.innerHTML || '';
          resolve(html);
        });
      });
    },

    getApiHtml() {
      if (window.__getHelpManualApiHtml) {
        return window.__getHelpManualApiHtml();
      }
      return new Promise(resolve => {
        let url;
        if (window.isLocalEnv) {
          const lang = this.getLang().toLowerCase();
          const LANG = lang.toUpperCase();
          url = `${helpConf.apiBaseUrl}?projectid=${helpConf.projectId}` +
            `&number=${lang}_topic_0000001259073050&version=&type=` +
            `&catalognumber=7&am=7&path=${LANG}_BOOKMAP_0000001306313197&deletenode=&baselineid=&tagname=` +
            `&startmapnumber=${LANG}_BOOKMAP_0000001306313197&username=xxx`;
          if (window.isLocalEnv) {
            url = url.replace(helpConf.origin, `/${window.visualEnv}`);
          }
        } else {
          const baseUrl = getHelpManualBaseUrl();
          const lang = this.getLang();
          const langLower = lang.toLowerCase();
          url = `${baseUrl}/${lang}/${langLower}_topic_0000001259073050.html`;
        }

        fetch(url).then(res=>res.text()).then(data=>{
          resolve(data);
        });
      });
    },

    getLang() {
      let lang = getLang();
      lang = lang.replace('_', '-');
      return lang;
    },

    async getTips() {
      const tipsObj = storage.get(STORAGE_KEY);
      const lang = this.getLang();
      if (tipsObj && tipsObj.lang === lang && new Date().getTime() - tipsObj.updateTime < STORAGE_TIMEOUT) {
        return tipsObj.tips;
      }

      const apiHtml = await this.getApiHtml();

      const tips = {};
      let docEl = document.createElement('div');
      docEl.innerHTML = xssValueFilter(apiHtml);

      const trs = docEl.querySelectorAll('tr');

      for (let i = 1; i < trs.length; i++) {
        const tr = trs[i];
        const tds = tr.querySelectorAll('td');
        if (tds.length) {
          const key = tds[0].innerText.trim();

          // 图片路径修正
          tds[2].querySelectorAll('img').forEach(n => {
            if (!n.src) {
              const href = n.getAttribute('data-hd-href') || '';
              const imgName = href.replace('x-wc://file=', '');
              const imgUrl = `${helpConf.imgBaseUrl}/1_${imgName}`;
              n.src = imgUrl;
            } else {
              const baseUrl = getHelpManualBaseUrl();
              const imgFile = n.src.split('/').pop();
              n.src = `${baseUrl}/${lang}/${imgFile}`;
            }
          });

          const isEmpty = tds[2].innerText.trim() === '(empty)';
          const html = isEmpty ? '' : tds[2].innerHTML;
          const tipHtml = xssValueFilter(html);
          tips[key] = tipHtml;
        }
      }
      docEl = null;
      storage.set(STORAGE_KEY, { tips, updateTime: new Date().getTime(), lang: this.getLang() });
      return tips;
    },
  },
};
</script>
<style lang="less">
.help-manual-snippet {
  max-width: 900px;
  .desc {
    p {
      margin-top: 0.4em;
      margin-bottom: 0.2em;
      min-height: 12px;
    }
  }
}
</style>
